package com.xyq.common.sucurity.interceptor;

import cn.hutool.core.util.StrUtil;
import com.xyq.common.core.constants.Constants;
import com.xyq.common.core.constants.HttpConstants;
import com.xyq.common.core.utils.ThreadLocalUtil;
import com.xyq.common.sucurity.service.TokenService;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

@Component
public class ExtendTokenInterceptor implements HandlerInterceptor {
    @Autowired
    private TokenService tokenService;
    @Value("${jwt.secret}")
    private String secret;   // 目前只有oj-system,所以拿到的是oj-system服务Nacos配置里的 secret

    @Override    // 1. 在请求到controller之前拦截
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        // 2. 获取token
         String token = getToken(request);
         // 先获取Claims , 提前把Token和secret处理了
        Claims claims = tokenService.getClaims(token, secret);
        // 判断延迟token
        tokenService.extendToken(claims);

         // 获取用户id , 保存到 ThreadLocal
        // 传一个 claims 来
        Long userId = tokenService.getUserId(claims);
        ThreadLocalUtil.set(Constants .USER_ID , userId);

        // 在ThreadLocal   存一份userKey 的 token唯一标识符
        String userKey = tokenService.getUserKey(claims);
        ThreadLocalUtil.set(Constants.USER_KEY , userKey) ;


        return true ;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
       // 在目标方法执行完后 , 清除 userid
        ThreadLocalUtil.remove();
    }

    /**
     * 从请求头中获取请求token
     *
     */         // 1. header中Authorization字段 里就是专门存储token的的地方
                              // 这个方法和 AuthFilter里的getToken是类似的
    private String getToken(HttpServletRequest request) {

        String token = request.getHeader(HttpConstants.AUTHENTICATION);
        // 如果前端设置了令牌前缀，则裁剪掉前缀         // Bearer请求头中 token可能会带有的前缀, 把这个Bearer前缀去除掉
        if (StrUtil.isNotEmpty(token) && token.startsWith(HttpConstants.PREFIX)) {
            token = token.replaceFirst(HttpConstants.PREFIX, StrUtil.EMPTY);
        }
        return token;
    }
}
